package cn.com.aisat.android.videoshow;

import java.util.ArrayList;
import java.util.List;

import cn.com.aisat.android.videoshow.adapter.GridViewAdapter;
import cn.com.aisat.android.videoshow.data.MovieItem;
import cn.com.aisat.android.videoshow.db.Utils;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.GridView;
import android.widget.TextView;

public class MainActivity extends Activity {
	private GridView maingridview;
	private GridViewAdapter gridviewadapter;
	private TextView menu_path_textview;
	private TextView page_num;
	private List<MovieItem> items;
	private int mNumColumn = 6, mPage = 0;
	private boolean consumed = false;
	private String lanpath = "高清电影/港台电影";
	private String  page="页号:";
	private static final int infokey = 165;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.main);
		init();
	}

	private void init() {
		maingridview = (GridView) findViewById(R.id.mian_gridview);
		maingridview.setOnKeyListener(onkeylistener);
		menu_path_textview = (TextView) findViewById(R.id.menu_path_textview);
		items = Utils.getItems();
		gridviewadapter = new GridViewAdapter(this, copy12ToListItem(items, 0));
		maingridview.setAdapter(gridviewadapter);
		menu_path_textview.setText(lanpath);
		maingridview.setOnItemSelectedListener(listener);
		page_num = (TextView) findViewById(R.id.page_num);
		page_num.setText(page+1+"/"+((items.size()%10)==0?(items.size()/10):((items.size()/10)+1)));
	}

	private int maingridview_position = 0;
	private OnItemSelectedListener listener = new OnItemSelectedListener() {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			maingridview_position = position;
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {

		}

	};

	private OnKeyListener onkeylistener = new View.OnKeyListener() {

		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			boolean consumed = false;
			if (event.getAction() == KeyEvent.ACTION_DOWN
					&& v.getId() == maingridview.getId()) {

				// int mTotalItems = maingridview.getCount();
				// Log.i("maingridview.getChildCount():", " --- " +
				// mTotalItems);
				// int mSelectedItemPosition = maingridview
				// .getSelectedItemPosition();
				// Log.i("maingridview.getSelectedItemPosition():", " --- "
				// + mSelectedItemPosition);
				//
				// int mPos = maingridview.getLastVisiblePosition();
				// Log.i("maingridview.getLastVisiblePosition():", " --- " +
				// mPos);
				//
				// int mFirst = maingridview.getFirstVisiblePosition();
				// Log.i("maingridview.getFirstVisiblePosition():", " --- "
				// + mFirst);
				//
				// int mFadeEdgeV = maingridview.getVerticalFadingEdgeLength();
				// int mFadeEdgeH =
				// maingridview.getHorizontalFadingEdgeLength();
				// Log.i("mFadeEdgeV : --- mFadeEdgeH :", "### :" + mFadeEdgeV
				// + " --- " + mFadeEdgeH);
				// int xGridWith = maingridview.getWidth();
				// int xGridgetHeight = maingridview.getHeight();
				//
				// int xWidth = maingridview.getChildAt(0) == null ? -1
				// : maingridview.getChildAt(0).getWidth();
				// Log.i("xGridWith : --- xGridgetHeight :", "### :" + xGridWith
				// + " --- " + xGridgetHeight);
				// int xHeight = maingridview.getChildAt(0) == null ? -1
				// : maingridview.getChildAt(0).getHeight();
				//
				// Log.i("xWidth : --- xHeight :", "### :" + xWidth + " --- "
				// + xHeight);
				// int columns = 0;
				// int rows = 0;
				// int totalrows = mTotalItems;
				// if (xWidth != 0 && xHeight != 0) {
				// columns = xGridWith / xWidth;
				// rows = xGridgetHeight / xHeight;
				// totalrows = mTotalItems / columns
				// + (mTotalItems % columns == 0 ? 0 : 1);
				// Log.i("Columns : --- Rows : --- total rows:", "### :"
				// + columns + " --- " + rows + "---" + totalrows);
				// Log.i("counts:", "---" + columns * rows);
				// }

				switch (keyCode) {
				case KeyEvent.KEYCODE_DPAD_DOWN:
					// doGridViewKeyDown(mSelectedItemPosition, rows, columns,
					// totalrows, mTotalItems);
					doGridViewKeyDown();
					consumed = true;
					break;
				case KeyEvent.KEYCODE_DPAD_UP:
					// doGridViewKeyUp(mSelectedItemPosition, rows, columns,
					// totalrows, mTotalItems);
					doGridViewKeyUp();
					consumed = true;
					break;
				case KeyEvent.KEYCODE_DPAD_LEFT:
					// doGridViewKeyLeft(mSelectedItemPosition, rows, columns,
					// totalrows, mTotalItems);
					doGridViewKeyLeft();
					consumed = true;
					break;
				case KeyEvent.KEYCODE_DPAD_RIGHT:
					// doGridViewKeyRight(mSelectedItemPosition, rows, columns,
					// totalrows, mTotalItems);
					doGridViewKeyRight();
					consumed = true;
					break;
				default:
					break;
				}
				if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == infokey)
						&& maingridview_position != -1) {
					Intent intent = new Intent(MainActivity.this,
							MovieShowActivity.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					intent.putExtra("item", items.get(maingridview_position));
					startActivity(intent);
					return true;
				}
				/*
				 * mSelectedItemPosition =
				 * maingridview.getSelectedItemPosition();
				 * Log.i("maingridview.getSelectedItemPosition():", " --- " +
				 * mSelectedItemPosition); mPos =
				 * maingridview.getLastVisiblePosition();
				 * Log.i("maingridview.getLastVisiblePosition():", " --- " +
				 * mPos);
				 */
			}

			return consumed;
		}

	};

	protected void doGridViewKeyUp() {
		int pos = maingridview.getSelectedItemPosition();
		int base = maingridview.getFirstVisiblePosition();
		int last = maingridview.getLastVisiblePosition();
		int size = items.size();
		int totalpage = size / (mNumColumn * 2)
				+ (size % (mNumColumn * 2) > 0 ? 1 : 0);
		int firstOfNextPage = (mPage - 1) * mNumColumn * 2;
		Log.i("firstOfNextPage,base,last,size", "---" + firstOfNextPage
				+ " -- " + base + "--" + last + "---" + size);
		Log.i("mPage,totalpage", "---" + mPage + "---" + totalpage);
		page_num.setText(page+mPage+"/"+totalpage);
		if (pos >= base + mNumColumn) {
			maingridview.setSelection(pos - base - mNumColumn);
			// 上一行
		} else {
			// 下一页
			if (firstOfNextPage < 0) {
				if (size <= mNumColumn * 2) {
					// 总个数小于一页，选中第一个。
					mPage = 0;
					return;
				} else {
					// 最后一页
					mPage = totalpage;
					firstOfNextPage = (totalpage - 1) * (mNumColumn * 2);
				}
			}
			mPage = mPage - 1;
			gridviewadapter = new GridViewAdapter(this, copy12ToListItem(items,
					firstOfNextPage));
			maingridview.setAdapter(gridviewadapter);
			if (gridviewadapter != null) {
				int end = gridviewadapter.getCount() - 1;
				maingridview.setSelection(end >= mNumColumn + pos - base ? mNumColumn + pos - base : pos - base);
			}
		}
	}

	protected void doGridViewKeyDown() {
		int pos = maingridview.getSelectedItemPosition();
		int base = maingridview.getFirstVisiblePosition();
		int last = maingridview.getLastVisiblePosition();
		int size = items.size();
		int totalpage = size / (mNumColumn * 2)
				+ (size % (mNumColumn * 2) > 0 ? 1 : 0);
		int firstOfNextPage = (mPage + 1) * mNumColumn * 2;
		Log.i("firstOfNextPage,base,last,size", "---" + firstOfNextPage
				+ " -- " + base + "--" + last + "---" + size);
		Log.i("mPage,totalpage", "---" + mPage + "---" + totalpage);
		page_num.setText(page+mPage+"/"+totalpage);
		int countsOfpage = 0;
		if (gridviewadapter != null) {
			countsOfpage = gridviewadapter.getCount() - 1;
		}
		if (pos <= base + mNumColumn && pos <= countsOfpage) {
			maingridview.setSelection(pos - base + mNumColumn);
			// 下一行
		} else {
			// 下一页
			if (firstOfNextPage > size) {
				if (size <= mNumColumn * 2) {
					// 总个数小于一页，选中第一个。
					mPage = 0;
					return;
				} else {
					// 第一页
					firstOfNextPage = 0;
					mPage = -1;
				}
			}
			mPage = mPage + 1;
			gridviewadapter = new GridViewAdapter(this, copy12ToListItem(items,
					firstOfNextPage));
			maingridview.setAdapter(gridviewadapter);
			Log.i("-----------------------------------------------","@@@@@@@@@@@@");
			if (gridviewadapter != null) {
				int end = gridviewadapter.getCount() - 1;
				maingridview.setSelection(end >= pos - base ? pos - base : end);
			}
		}
	}

	protected void doGridViewKeyRight() {
		int pos = maingridview.getSelectedItemPosition();
		int base = maingridview.getFirstVisiblePosition();
		int last = maingridview.getLastVisiblePosition();
		int size = items.size();
		int totalpage = size / (mNumColumn * 2)
				+ (size % (mNumColumn * 2) > 0 ? 1 : 0);
		int firstOfNextPage = (mPage + 1) * mNumColumn * 2;
		Log.i("firstOfNextPage,base,last,size", "---" + firstOfNextPage
				+ " -- " + base + "--" + last + "---" + size);
		Log.i("mPage,totalpage", "---" + mPage + "---" + totalpage);
		page_num.setText(page+mPage+"/"+totalpage);
		if (pos >= base && pos < last) {
			// 下一个
			maingridview.setSelection(pos + 1 - base);
		} else {
			// 下一页
			if (firstOfNextPage > size) {

				if (size <= mNumColumn * 2) {
					// 总个数小于一页，选中第一个。
					maingridview.setSelection(base);
					mPage = 0;
					return;
				} else {
					// 第一页
					firstOfNextPage = 0;
					mPage = -1;
				}
			}
			mPage = mPage + 1;
			gridviewadapter = new GridViewAdapter(this, copy12ToListItem(items,
					firstOfNextPage));

			maingridview.setAdapter(gridviewadapter);
			Log.i("false!", "pos >= base && pos < last");
			maingridview.setSelection(0);
		}

	}

	protected void doGridViewKeyLeft() {
		// TODO Auto-generated method stub
		int pos = maingridview.getSelectedItemPosition();
		int base = maingridview.getFirstVisiblePosition();
		int last = maingridview.getLastVisiblePosition();
		int size = items.size();
		int totalpage = size / (mNumColumn * 2)
				+ (size % (mNumColumn * 2) > 0 ? 1 : 0);
		int firstOfNextPage = (mPage - 1) * mNumColumn * 2;
		Log.i("firstOfNextPage,base,last,size", "---" + firstOfNextPage
				+ " -- " + base + "--" + last + "---" + items.size());
		Log.i("mPage,totalpage", "---" + mPage + "---" + totalpage);
		page_num.setText(page+mPage+"/"+totalpage);
		if (pos > base && pos <= last) {
			maingridview.setSelection(pos - 1 - base);
			// 上一个
		} else {
			// 下一页
			if (firstOfNextPage < 0) {

				if (size <= mNumColumn * 2) {
					// 总个数小于一页，选中最后一个。
					maingridview.setSelection(last);
					mPage = 0;
					return;
				} else {
					mPage = totalpage;
					firstOfNextPage = (totalpage - 1) * (mNumColumn * 2);
				}
			}
			mPage = mPage - 1;
			gridviewadapter = new GridViewAdapter(this, copy12ToListItem(items,
					firstOfNextPage));
			maingridview.setAdapter(gridviewadapter);
			if (gridviewadapter != null) {
				maingridview.setSelection(gridviewadapter.getCount() - 1);
			}

		}
	}

	protected void doGridViewKeyUp(int basePos, int row, int column,
			int totalRows, int totalItems) {
		Log.i("basePos,row,column,totalRows,totalItems", " values: " + basePos
				+ " _ " + row + " _ " + column + " _ " + totalRows + " _ "
				+ totalItems);
		consumed = false;
		// int totalPage = totalItems / (row * column) + totalItems % (row *
		// column) == 0 ? 0:1;
		int currentPage = (basePos + 1) / (row * column)
				+ ((basePos + 1) % (row * column) == 0 ? 0 : 1);
		Log.i("CurrentPage:", " ---- " + currentPage);
		page_num.setText(page+currentPage+"/"+totalRows);
		if (basePos - column < 0) {
			// 在第一页，第一行；返回到最后一页，对应位置。
			maingridview.setSelection(column == 0 ? 0 : totalItems - column
					+ (basePos % column));
			consumed = true;
		} else if (basePos - column > (currentPage) * (row * column)) {
			// 不在最后一页，也不在最后一行；跳到上一个，对应位置。
			maingridview.setSelection(column == 0 ? 0 : (basePos - column));
			consumed = true;
		} else if (basePos - column <= (currentPage) * (row * column)) {
			maingridview
					.smoothScrollToPosition((currentPage - 2) > 0 ? (currentPage - 2)
							* (row * column)
							: 0);
			maingridview.setSelection(column == 0 ? 0 : (currentPage - 1)
					* (row * column) + (basePos % column));
			consumed = true;
		}

	}

	private void doGridViewKeyDown(int basePos, int row, int column,
			int totalRows, int totalItems) {
		Log.i("basePos,row,column,totalRows,totalItems", " values: " + basePos
				+ " _ " + row + " _ " + column + " _ " + totalRows + " _ "
				+ totalItems);
		consumed = false;
		int currentPage = (basePos + 1) / (row * column)
				+ ((basePos + 1) % (row * column) == 0 ? 0 : 1);
		Log.i("CurrentPage:", " ---- " + currentPage);
		page_num.setText(page+mPage+"/"+totalRows);
		if (basePos + column >= totalItems) {
			// 在最后一页，最后一行；返回到第一页，对应位置。
			maingridview.setSelection(column == 0 ? 0 : (basePos % column));
			consumed = true;
		} else if (basePos + column < (currentPage + 0) * (row * column)) {
			Log.i("Down---Down---Down", "11111111111111111111111111111111");
			// 不在最后一页，也不在最后一行；跳到下一个，对应位置。
			maingridview.setSelection(column == 0 ? 0 : (basePos + column));
			consumed = true;
		} else if (basePos + column >= (currentPage + 0) * (row * column)) {
			Log.i("Down---Down---Down", "222222222222222111111111111111111111");
			maingridview
					.smoothScrollToPosition((currentPage + 1) > totalRows ? 0
							: (currentPage + 1) * (row * column) - 1);
			maingridview.setSelection(column == 0 ? 0 : (currentPage + 1)
					* (row * column) + (basePos % column));
			consumed = true;
		}

	}

	private void doGridViewKeyLeft(int basePos, int row, int column,
			int totalRows, int totalItems) {
		Log.i("basePos,row,column,totalRows,totalItems", " values: " + basePos
				+ " _ " + row + " _ " + column + " _ " + totalRows + " _ "
				+ totalItems);
		consumed = false;
		int currentPage = (basePos + 1) / (row * column)
				+ ((basePos + 1) % (row * column) == 0 ? 0 : 1);
		Log.i("CurrentPage:", " ---- " + currentPage);
		page_num.setText(page+currentPage+"/"+totalRows);
		if (basePos - 1 < 0) {
			// 在第一页，第一个；返回到尾。
			maingridview.setSelection(totalItems - 1);
			consumed = true;
		} else if (basePos - 1 < (currentPage - 1) * (row * column)) {
			Log.i("left---left---left", "11111111111111111111111111111111");

			maingridview
					.smoothScrollToPosition((currentPage - 2) > 0 ? (currentPage - 2)
							* (row * column)
							: 0);
			// maingridview.setSelection((currentPage - 2) > 0 ? (currentPage -
			// 2)*(row * column):0);
			maingridview.setSelection(basePos - 1);
			consumed = true;
		} else if (basePos - 1 < currentPage * (row * column)) {
			maingridview.setSelection(basePos - 1);
			consumed = true;
		}
	}

	protected void doGridViewKeyRight(int basePos, int row, int column,
			int totalRows, int totalItems) {
		Log.i("basePos,row,column,totalRows,totalItems", " values: " + basePos
				+ " _ " + row + " _ " + column + " _ " + totalRows + " _ "
				+ totalItems);
		consumed = false;
		int currentPage = (basePos + 1) / (row * column)
				+ ((basePos + 1) % (row * column) == 0 ? 0 : 1);
		Log.i("CurrentPage:", " ---- " + currentPage);
		page_num.setText(page+currentPage+"/"+totalRows);
		if (basePos + 1 >= totalItems) {
			// 在最后一页，最后一个；返回到第一页，对应位置。
			maingridview.setSelection(0);
			consumed = true;
		} else if (basePos + 1 >= (currentPage + 0) * (row * column)) {
			Log.i("right---right---right", "11111111111111111111111111111111");
			maingridview.smoothScrollToPosition((currentPage) > totalRows ? 0
					: (currentPage + 1) * (row * column) - 1);
			// maingridview.setSelection((currentPage) > totalRows ?
			// 0:(currentPage + 1)*(row * column) - 1);
			maingridview.setSelection((currentPage + 1) >= totalItems ? 0
					: basePos + 1);
			consumed = true;
		} else if (basePos + 1 < (currentPage + 1) * (row * column)) {
			maingridview.setSelection(basePos + 1);
			consumed = true;
		}

	}

	/**
	 * 复制list的数据到item中去，用于显示用的，list为主要的源数据源， pos就第一页的最后一个或是最前一个
	 * 这是不去判断是最后一个还是最前面一个。以后再说
	 * 
	 * @param list
	 * @param pos
	 */
	public List<MovieItem> copy12ToListItem(List<MovieItem> list, int pos) {
		int size = list.size();
		List<MovieItem> item2 = new ArrayList<MovieItem>();
		for (int i = 0; i < 12; i++) {
			if (pos < size) {
				MovieItem item = list.get(pos);
				item2.add(item);
				pos = pos + 1;
			}
		}
		return item2;
	}
}